package com.exle.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;

import com.exle.domain.Role;
import com.exle.domain.User;
import com.exle.persistence.UserMapper;

@Service
public class UserService {
	@Autowired
	private UserMapper userMapper;

	public List<User> getUsers() {
		List<User> users = userMapper.getUsers();
		for (User u : users) {
			u.setRoles(userMapper.getRolesByUserId(u.getId()));
		}
		return users;
	}

	public User getUser(String username) {
		return userMapper.getUserByName(username);
	};

	public List<Role> getRoles(String user_id) {
		return userMapper.getRolesByUserId(user_id);
	};

	public List<GrantedAuthority> getGrantedAuthorities(String username) {

		List<Role> rs = userMapper.getRolesByUserName(username);
		List<GrantedAuthority> as = new ArrayList<GrantedAuthority>();

		for (Role r : rs) {
			as.add(new SimpleGrantedAuthority(r.getAuthority()));
		}
		return as;
	}

	public String getPasswordByUsername(String username) {
		return userMapper.getPasswordByUsername(username);
	}

	public String[] getRolesByUrl(String url) {
		return userMapper.getRolesByUrl(url);
	}
}
